-- Create tables in punimtag_auth database
-- Run this after the database is created: psql -d punimtag_auth -f setup-auth-tables.sql

-- Create users table
CREATE TABLE IF NOT EXISTS users (
    id SERIAL PRIMARY KEY,
    email VARCHAR(255) UNIQUE NOT NULL,
    name VARCHAR(255),
    password_hash VARCHAR(255) NOT NULL,
    is_admin BOOLEAN DEFAULT FALSE,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Create pending_identifications table
-- Note: face_id references faces in the punimtag database, but we can't use a foreign key
-- across databases. The application will validate that faces exist.
CREATE TABLE IF NOT EXISTS pending_identifications (
    id SERIAL PRIMARY KEY,
    face_id INTEGER NOT NULL,
    user_id INTEGER NOT NULL,
    first_name VARCHAR(255) NOT NULL,
    last_name VARCHAR(255) NOT NULL,
    middle_name VARCHAR(255),
    maiden_name VARCHAR(255),
    date_of_birth DATE,
    status VARCHAR(50) DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

-- Create indexes
CREATE INDEX IF NOT EXISTS idx_pending_identifications_face_id ON pending_identifications(face_id);
CREATE INDEX IF NOT EXISTS idx_pending_identifications_user_id ON pending_identifications(user_id);
CREATE INDEX IF NOT EXISTS idx_pending_identifications_status ON pending_identifications(status);

-- Create pending_linkages table to track tag submissions
CREATE TABLE IF NOT EXISTS pending_linkages (
    id SERIAL PRIMARY KEY,
    photo_id INTEGER NOT NULL,
    tag_id INTEGER,
    tag_name VARCHAR(255),
    user_id INTEGER NOT NULL,
    status VARCHAR(50) DEFAULT 'pending',
    notes TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_pending_linkages_photo_id ON pending_linkages(photo_id);
CREATE INDEX IF NOT EXISTS idx_pending_linkages_tag_id ON pending_linkages(tag_id);
CREATE INDEX IF NOT EXISTS idx_pending_linkages_user_id ON pending_linkages(user_id);
CREATE INDEX IF NOT EXISTS idx_pending_linkages_status ON pending_linkages(status);

