DROP TABLE IF EXISTS place_pages CASCADE;
-- Slett gamle tabeller slik at vi starter med helt blanke ark
DROP TABLE IF EXISTS hole_lengths CASCADE;
DROP TABLE IF EXISTS holes CASCADE;
DROP TABLE IF EXISTS tees CASCADE;
DROP TABLE IF EXISTS courses CASCADE;
DROP TABLE IF EXISTS facilities CASCADE;

-- 1. Tabellen for ANLEGG (Fasilitet)
CREATE TABLE facilities (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    slug VARCHAR(255) UNIQUE NOT NULL,
    description TEXT,
    established_year INTEGER,
    season VARCHAR(255),
    address VARCHAR(255),
    zipcode VARCHAR(50),
    city VARCHAR(255),
    county VARCHAR(255),
    lat DOUBLE PRECISION,
    lng DOUBLE PRECISION,
    email VARCHAR(255),
    phone VARCHAR(255),
    website_url VARCHAR(255),
    golfbox_booking_url VARCHAR(255),
    golfbox_tournament_url VARCHAR(255),
    cooperating_clubs JSONB DEFAULT '[]'::jsonb,
    facebook_url VARCHAR(255),
    instagram_url VARCHAR(255),
    weather_url VARCHAR(255),
    webcam_url VARCHAR(255),
    golfamore BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE place_pages (
    slug VARCHAR(255) PRIMARY KEY,
    factbox_intro_html TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 2. Tabellen for BANER (Tilhører et anlegg)
CREATE TABLE courses (
    id SERIAL PRIMARY KEY,
    facility_id INTEGER REFERENCES facilities(id) ON DELETE CASCADE,
    name VARCHAR(255) NOT NULL,
    holes INTEGER,
    physical_hole_count INTEGER,
    include_in_physical_hole_total BOOLEAN NOT NULL DEFAULT TRUE,
    par INTEGER,
    length_meters INTEGER,
    course_type VARCHAR(255),
    architect VARCHAR(255),
    status VARCHAR(255),
    is_main_course BOOLEAN DEFAULT TRUE,
    is_visible BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 3. Tabellen for UTSLAG (Tilhører en bane)
CREATE TABLE tees (
    id SERIAL PRIMARY KEY,
    course_id INTEGER REFERENCES courses(id) ON DELETE CASCADE,
    name VARCHAR(50) NOT NULL, -- F.eks. '64', 'Gul', 'Rød'
    sort_order INTEGER NOT NULL DEFAULT 0,
    cr_men NUMERIC(4, 1),
    slope_men INTEGER,
    cr_women NUMERIC(4, 1),
    slope_women INTEGER
);

-- 4. Tabellen for HULL (Tilhører en bane)
CREATE TABLE holes (
    id SERIAL PRIMARY KEY,
    course_id INTEGER REFERENCES courses(id) ON DELETE CASCADE,
    hole_number INTEGER NOT NULL,
    par INTEGER,
    hcp_index INTEGER
);

-- 5. Tabellen for LENGDER (Knytter et hull til et spesifikt utslag)
CREATE TABLE hole_lengths (
    id SERIAL PRIMARY KEY,
    hole_id INTEGER REFERENCES holes(id) ON DELETE CASCADE,
    tee_id INTEGER REFERENCES tees(id) ON DELETE CASCADE,
    length_meters INTEGER
);

CREATE UNIQUE INDEX hole_lengths_hole_tee_uidx ON hole_lengths (hole_id, tee_id);
