-- V001 - Initial Schema for TaxBaik

CREATE TABLE categories (
    id         SERIAL PRIMARY KEY,
    name       VARCHAR(100) NOT NULL,
    slug       VARCHAR(100) NOT NULL UNIQUE,
    sort_order INT NOT NULL DEFAULT 0
);

CREATE TABLE admin_users (
    id            SERIAL       PRIMARY KEY,
    username      VARCHAR(100) NOT NULL UNIQUE,
    password_hash VARCHAR(500) NOT NULL,
    last_login_at TIMESTAMPTZ,
    created_at    TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);

CREATE TABLE blog_posts (
    id              SERIAL       PRIMARY KEY,
    title           VARCHAR(300) NOT NULL,
    content         TEXT         NOT NULL,
    slug            VARCHAR(300) NOT NULL UNIQUE,
    category_id     INT          REFERENCES categories(id) ON DELETE SET NULL,
    tags            TEXT,
    author_id       INT          REFERENCES admin_users(id) ON DELETE SET NULL,
    published_at    TIMESTAMPTZ,
    view_count      INT          NOT NULL DEFAULT 0,
    seo_title       VARCHAR(300),
    seo_description VARCHAR(500),
    thumbnail_url   VARCHAR(500),
    is_published    BOOLEAN      NOT NULL DEFAULT FALSE,
    created_at      TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
    updated_at      TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_blog_slug      ON blog_posts(slug);
CREATE INDEX idx_blog_published ON blog_posts(is_published, published_at DESC);
CREATE INDEX idx_blog_category  ON blog_posts(category_id);

CREATE TABLE inquiries (
    id           SERIAL       PRIMARY KEY,
    name         VARCHAR(100) NOT NULL,
    phone        VARCHAR(20)  NOT NULL,
    email        VARCHAR(200),
    service_type VARCHAR(100) NOT NULL,
    message      TEXT         NOT NULL,
    status       VARCHAR(50)  NOT NULL DEFAULT 'new',
    ip_address   VARCHAR(50),
    created_at   TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_inquiry_status  ON inquiries(status);
CREATE INDEX idx_inquiry_created ON inquiries(created_at DESC);

CREATE TABLE site_settings (
    key        VARCHAR(200) PRIMARY KEY,
    value      TEXT         NOT NULL,
    updated_at TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);
